package com.lzx.adx.report.controller.v1.youyou;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.model.youyou.YouYouRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.AdPerUtil;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import com.lzx.adx.report.util.helper.YtyHeper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 媒体：优优
 * 产品 高德
 */
@RequestMapping("/yy/xly/gd")
@RestController
@Slf4j
public class YouYouGdReportController {

    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;


    @GetMapping("/report")
    public ResponseEntity report(YouYouRequest youYouRequest) {
        log.info("接收到优新义互联-高德地图的请求参数为{}", JsonUtils.toJsonString(youYouRequest));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(youYouRequest);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setCallback(youYouRequest.getCallbackUrl());
        reportDTO.setExtend(JsonUtils.toJsonString(youYouRequest));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        reportDTO.setImeiSum(youYouRequest.getImeiMd5());
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(youYouRequest.getDspId());
        String finalUrl = covertXyGd(accountDTO, reportDTO,youYouRequest);
        log.info("账号为{},完整的新义互联-高德地图-1请求地址为{}", youYouRequest.getDspId(), finalUrl);
        //2.2夸克上报接口
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{} 完整的新义互联-高德地图-1的接口，响应的结果为{}", youYouRequest.getDspId(), body);
        return ResponseEntity.ok(new Result());
    }



    /**
     * 新联义-高德-yoyo
     *
     * @param requestId 请求参数
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/xly/callback")
    public ResponseEntity ytCallBackUrl(String requestId, String event_type) throws Exception {
        log.info("优优收到优新义互联-高德地图的回调信息，请求流水号{},回调类型为{}", requestId, event_type);
        if (StringUtils.isBlank(requestId)) {
            log.info("优优收到优新义互联-高德地图的回调信息，请求流水号空");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        if (StringUtils.isBlank(event_type)) {
            log.info("优优收到优新义互联-高德地图的回调信息，转换类型空");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        String time = String.valueOf(System.currentTimeMillis());
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
        } else {
            log.error("回传流水号{}，系统当前不存在", requestId);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }


        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String transformType = jsonObject.getString(event_type);
        if (StringUtils.isBlank(transformType)){
            log.info("优优收到优新义互联-高德地图的回调信息当前流水号：{}，事件类型{}不合法，不做数据回传", requestId,event_type);
            return ResponseEntity.ok(new Result());
        }
        reportDTO.setResultType(event_type);
        reportDTO.setResultTime(time);
        reportDTO.setUpdateTime(new Date());
        reportService.updateData(reportDTO,event_type);
        Double per = jsonObject.getDouble("per");
        if (Objects.nonNull(per)) {
            if(!AdPerUtil.randomPer(per)) {
                log.info("账户{}流水号{}超出了比例,不做回传", reportDTO.getDspId(), reportDTO.getBizRequestId());
                return ResponseEntity.ok(new Result());
            }
        }
        //3，获取回传地址，进行解码
        String decodeUrl = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        //拼接完整的请求参数
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("transformType", transformType);
        String finalUrl = decodeUrl + "&" + URLUtil.buildQuery(paramsReq, StandardCharsets.UTF_8);
        log.info("dspId{},请求流水号{}优新义互联-高德地图回调优优的完整地址为：{}", reportDTO.getDspId(), requestId, finalUrl);
        String result = HttpUtil.get(finalUrl);
        log.info("dspId{},请求流水号{}优新义互联-高德地图回调优优的结果为：{}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }







    /**
     * 新义高德
     * @param accountDTO
     * @param reportDTO
     */
    public String covertXyGd(AccountDTO accountDTO,ReportDTO reportDTO,YouYouRequest youYouRequest){
        Map<String,Object> params=new HashMap<>();
        params.put("action",reportDTO.getEventType());
        params.put("ad_id",reportDTO.getContentId());
        params.put("campaign_id",reportDTO.getCampaignId());
        params.put("idfa",youYouRequest.getIdfa());
        params.put("idfa_md5",youYouRequest.getIdfaMd5());
        params.put("imei",youYouRequest.getImei());
        params.put("imei_md5",youYouRequest.getImeiMd5());
        params.put("oaid",youYouRequest.getOaid());
        params.put("oaid_md5",youYouRequest.getOaidMd5());
        params.put("os_type",youYouRequest.getOs());
        params.put("ip",youYouRequest.getIp());
        params.put("ua", StringUtils.isNotBlank(reportDTO.getUser_agent()) ? URLUtil.encode(reportDTO.getUser_agent()) : "");
        params.put("request_id",reportDTO.getBizRequestId());

        String callbackUrl = String.format(accountDTO.getDspCallbackUrl(), reportDTO.getBizRequestId());
        String urlParams = URLUtil.buildQuery(params, StandardCharsets.UTF_8) + "&callback_url=" + URLEncoderDecoderTool.encodeURL(callbackUrl);
        return accountDTO.getDspReportUrl() + "&" + urlParams;
    }


}
